package com.museum.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.museum.common.dto.AudioDto;
import com.museum.common.lang.Result;
import com.museum.config.MinioConfig;
import com.museum.entity.Wordentry;
import com.museum.service.IWordentryService;
import com.museum.utils.MinioUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Akihi
 * @since 2022-12-09
 */
@Slf4j
@RestController
@RequestMapping("sys/audio")
public class AudioController {
    @Autowired
    private IWordentryService wordentryService;
    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private MinioConfig minioConfig;

    @GetMapping("list")
    public Result list(String mandarin, Long current, Long size) {
        /*如果name为空，则查全部*/
        Page<Wordentry> pageData = wordentryService.page(
                new Page<>(current, size),
                new QueryWrapper<Wordentry>()
                        .like(StrUtil.isNotBlank(mandarin), "mandarin", mandarin)
        );
        /*log.info("分页查询音频");*/
        return Result.success(pageData);
    }

    @PostMapping("save")
    public Result save(AudioDto audioDto) {
        String newFileName;
        try {
            MultipartFile file = audioDto.getFile();
            //原文件名
            String fileName = file.getOriginalFilename();
            log.info("fileName----》{}", fileName);
            //新文件名： 当前时间毫秒数 + 源文件后缀
            String folder = "/mp3/";
            newFileName = folder + System.currentTimeMillis() + "." + StrUtil.subAfter(fileName, ".", true);
            log.info("newFileName----》{}", newFileName);
            //文件类型
            String contentType = file.getContentType();
            log.info("contentType: {}", contentType);
            /*文件类型判断mp3*/
            String[] correctContentType = new String[1];
            correctContentType[0] = "audio/mpeg";
            if (!StrUtil.containsAny(contentType, correctContentType)) {
                log.error("上传失败，请选择正确的文件类型");
                return Result.fail("上传失败，请选择正确的文件类型");
            }
            minioUtils.uploadFile(minioConfig.getBucketName(), file, newFileName, contentType);
        } catch (Exception e) {
            log.error("上传失败，服务繁忙");
            return Result.fail("上传失败，服务繁忙");
        }
        /*数据库新增*/
        Wordentry wordentry = new Wordentry()
                .setMandarin(audioDto.getMandarin())
                .setHakka(audioDto.getHakka())
                .setHakkaPronunciation(newFileName)
                .setPlace(audioDto.getPlace());
        wordentryService.save(wordentry);
        log.info("新增成功");
        return Result.success("新增成功");
    }
    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id) {
        log.info("id====>{}", id);
        Wordentry wordentry = wordentryService.getById(id);
        log.info("wordentry====>{}", wordentry);
        return Result.success(wordentry);
    }
    /*仅对相关字段进行修改，不支持音频修改*/
    @PostMapping("update")
    public Result update(AudioDto audioDto){
        Wordentry wordentry = new Wordentry()
                .setId(audioDto.getId())
                .setMandarin(audioDto.getMandarin())
                .setHakka(audioDto.getHakka())
                .setPlace(audioDto.getPlace());
        boolean isSuccess = wordentryService.updateById(wordentry);
        if (isSuccess){
            return Result.success("修改成功");
        }else {
            return Result.fail("请稍后重试");
        }
    }
    @PostMapping("/delete")
    public Result info(@RequestBody Long[] ids) {
        /*批量删除文件*/
        List<String> keys = wordentryService.getHakkaPronunciationsByIds(ids);
        minioUtils.removeFiles(minioConfig.getBucketName(), keys);
        /*删除记录*/
        wordentryService.removeByIds(Arrays.asList(ids));
        return Result.success("删除成功");
    }
}
